// localLifePackage/pages/businessInfo/businessInfo.js
var common = require("../../../common/common.js").common;

var leader = require("../../../common/leader.js").leader;

var WxParse = require("../../../wxParse/wxParse.js");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        business_id: null,
        //商户id
        current: "tab1",
        notice_modal_show: false,
        productList: [],
        moudle_name: "",
        top_address: "",
        page: 1,
        rows: 10,
        myleaderinfo: [],
        cartBox: 0,
        alert: 0,
        buy_num: 1,
        style: 1,
        total_amount: "0.00",
        pageSuper: 1,
        supperMarketGoods: [],
        scrollTop: "",
        businessListFlag: true,
        position: "",
        header_show: false,
        businessInfoTag: {},
        businessInfo: {}
    },
    handleChange({detail: detail}) {
        this.setData({
            current: detail.key
        });
        if (this.data.current == "tab1") {
            this.getfirstClass();
            //获得商超一级分类
                } else {
            this.getBusinessInfo();
            //获取商品列表信息
                }
    },
    /**
   * 更多公告
  */
    more_notice() {
        this.setData({
            notice_modal_show: true
        });
    },
    /**
   * 隐藏公告
  */
    noticeCancel() {
        this.setData({
            notice_modal_show: false
        });
    },
    //获取去右侧胶囊的信息
    getHeader() {
        let menuRect = wx.getMenuButtonBoundingClientRect();
        this.setData({
            topBarHeight: menuRect.height,
            topBarTop: menuRect.top
        });
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        this.getHeader();
        this.setData({
            initOptions: options
        });
        wx.showShareMenu({
            // withShareTicket: true,
            menus: [ "shareAppMessage", "shareTimeline" ]
        });
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        if (options.merchant_id) {
            this.setData({
                id: options.merchant_id
            });
        } else {
            wx.showModal({
                title: "提示",
                content: "暂无此商家，返回商家列表！",
                showCancel: false,
                success: function() {
                    wx.redirectTo({
                        url: "/localLifePackage/pages/businessList/businessList"
                    });
                }
            });
        }
        this.getBase();
        leader.getMyLeaderInfo();
        //公用方法团长请求
                this.getBusinessDetail();
        //获取商家列信息
                this.getModeName();
        this.getCateList();
        //获取购物车
        },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {
        console.log(wx.getSystemInfoSync().windowHeight);
        let height = wx.getSystemInfoSync().windowHeight - 120;
        this.setData({
            scrollTop: height * 2
        });
    },
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        this.onLoad(this.data.initOptions);
        wx.stopPullDownRefresh();
    },
    onPageScroll: function(e) {
        let that = this;
        const query = wx.createSelectorQuery().in(this);
        query.select(".classfit_right_view").boundingClientRect();
        query.selectViewport().scrollOffset();
        query.exec(function(res) {
            if (res[0]) {
                var scrollLen = 50;
                if (res[0].top <= scrollLen) {
                    that.setData({
                        position: "fixed",
                        header_show: true
                    });
                } else {
                    that.setData({
                        position: "",
                        header_show: false
                    });
                }
            }
        });
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {
        if (this.data.current == "tab1") {
            this.getfirstClass();
            //获得商超一级分类
            // wx.showLoading({
            //   title: '加载中...',
            // })
                        this.setData({
                businessListFlag: true
            });
            //this.getSuperMarketGoods()
                } else {
            this.getBusinessInfo();
            //获取商品列表信息
                }
    },
    onShareTimeline: function() {
        let that = this;
        return {
            title: that.data.name,
            imageUrl: that.data.cover,
            // 图片 URL
            query: "merchant_id=" + that.data.id
        };
    },
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {
        let that = this;
        return {
            title: that.data.name,
            imageUrl: that.data.cover,
            path: "/localLifePackage/pages/businessInfo/businessInfo?merchant_id=" + that.data.id
        };
    },
    //全局基础配置信息
    getBase: function(openid) {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                that.setData({
                    color_header: res.extra.color_header,
                    color_text: res.extra.color_text,
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor
                });
                console.log(res.extra.color_main);
                // wx.setNavigationBarColor({
                //   frontColor: '#ffffff',
                //   backgroundColor: that.data.color_main,
                // })
                        }
        });
    },
    //一级分类
    getfirstClass() {
        console.log(312312312);
        var that = this;
        common.request({
            endpoint: "v1/Supermarket/product-category/first-category",
            method: "post",
            data: {
                business_id: that.data.id
            },
            success: res => {
                var classift = res.extra;
                var choosePid = that.data.choosePid ? that.data.choosePid : classift.length ? classift[0].id : "";
                that.setData({
                    classift: classift,
                    choosePid: choosePid,
                    classfitHeight: classift.length * 100
                });
                if (choosePid) {
                    that.getSecondClass();
                }
            }
        });
    },
    //选择分类
    chooseClass: function(e) {
        this.setData({
            choosePid: e.currentTarget.dataset.id,
            subClassify: [],
            supperMarketGoods: [],
            page: 1,
            pageSuper: 1
        });
        this.getSecondClass();
    },
    //获得二级分类
    getSecondClass: function() {
        var that = this;
        common.request({
            endpoint: "v1/Supermarket/product-category/second-category",
            method: "post",
            data: {
                business_id: that.data.id,
                parent_id: that.data.choosePid
            },
            success: res => {
                var subClassify = res.extra;
                that.setData({
                    subClassify: subClassify,
                    chooseSubPid: subClassify.length ? subClassify[0].id : ""
                });
                if (subClassify.length) {
                    that.getSuperMarketGoods();
                } else {
                    that.setData({
                        businessListFlag: false
                    });
                }
            }
        });
    },
    //选择二级分类
    chooseSubClasss: function(e) {
        this.setData({
            chooseSubPid: e.currentTarget.dataset.id,
            pageSuper: 1,
            supperMarketGoods: []
        });
        this.getSuperMarketGoods();
    },
    //商超商品
    getSuperMarketGoods: function() {
        this.setData({
            businessListFlag: true
        });
        var that = this;
        common.request({
            endpoint: "v1/Supermarket/product",
            method: "post",
            data: {
                business_id: that.data.id,
                category_second_id: that.data.chooseSubPid,
                parent_id: that.data.choosePid,
                page: that.data.pageSuper
            },
            success: res => {
                var supperMarketGoods = res.extra.rows;
                that.setData({
                    supperMarketGoods: that.data.supperMarketGoods.concat(supperMarketGoods),
                    pageSuper: that.data.pageSuper + 1,
                    businessListFlag: false
                });
                //wx.hideLoading()
                                if (supperMarketGoods.length == 0) {
                    wx.showToast({
                        title: "商品全部加载完",
                        icon: "success",
                        duration: 1e3
                    });
                }
            }
        });
    },
    searchBusiness(e) {
        let keyword = e.detail.value;
        let productList = this.data.productList;
        productList.map(function(v, i) {
            let itemHidden;
            if (v.product_name.match(keyword)) {
                itemHidden = false;
            } else {
                itemHidden = true;
            }
            return Object.assign(v, {
                itemHidden: itemHidden
            });
        });
        this.setData({
            productList: productList
        });
    },
    getBusinessDetail() {
        var that = this;
        common.request({
            endpoint: "Localbusiness/merchant/merchant-find",
            method: "post",
            data: {
                id: that.data.id
            },
            success: res => {
                // console.log(res);
                that.setData({
                    businessInfo: res.extra,
                    name: res.extra.name,
                    //商家名称
                    cover: res.extra.cover,
                    //商家封面
                    announcement: res.extra.announcement ? res.extra.announcement : "-",
                    //商家公告
                    address: res.extra.address_name,
                    //商家地址
                    detail: WxParse.wxParse("detail", "html", res.extra.detail ? res.extra.detail : "", this, 0),
                    //商家描述
                    phone: res.extra.phone,
                    //商家电话
                    time: res.extra.start_time + "-" + res.extra.end_time,
                    //商家营业时间
                    business_qualifications: res.extra.business_qualifications.split(","),
                    //商家资质
                    is_alive: res.extra.is_alive,
                    //商家营业休息
                    face_pay: res.extra.face_pay,
                    open_module: res.extra.open_module,
                    qualifications_display: res.extra.qualifications_display
                });
                if (res.extra.open_module == 2) {
                    that.setData({
                        current: "tab2"
                    });
                }
                common.request({
                    endpoint: `v1/Localbusiness/merchant/view?id=${that.data.id}`,
                    method: "post",
                    data: {},
                    success: res => {
                        // console.log(res);
                        that.setData({
                            businessInfoTag: res.extra,
                            style: res.extra.vendor_style
                        });
                        if (that.data.current == "tab1") {
                            that.getfirstClass();
                            //获得商超一级分类
                                                } else {
                            that.getBusinessInfo();
                            //获取商品列表信息
                                                }
                    },
                    fail() {
                        wx.showModal({
                            title: "提示",
                            content: "暂无此商家，返回商家列表！",
                            showCancel: false,
                            success: function() {
                                wx.redirectTo({
                                    url: "/localLifePackage/pages/businessList/businessList"
                                });
                            }
                        });
                    }
                });
            },
            fail() {
                wx.showModal({
                    title: "提示",
                    content: "暂无此商家，返回商家列表！",
                    showCancel: false,
                    success: function() {
                        wx.redirectTo({
                            url: "/localLifePackage/pages/businessList/businessList"
                        });
                    }
                });
            }
        });
    },
    //团购商品
    getBusinessInfo() {
        var that = this;
        that.setData({
            businessListFlag: true
        });
        common.request({
            endpoint: "Localbusiness/product/product-list",
            method: "post",
            data: {
                page_size: that.data.rows,
                page: that.data.page,
                business_id: that.data.id
            },
            success: res => {
                // console.log(res);
                var proData = [];
                res.extra.map(x => {
                    let banner = x.banner.split(",");
                    x.banner = banner[0];
                    x.really_sale = Number(x.virtual_monthly_sales) + Number(x.sale_volume);
                    if (x.stock <= 0) {
                        x.bu_noTitle = "库存不足";
                    } else {
                        x.bu_noTitle = "立即购买";
                    }
                    let leader_brokerage = Number(x.leader_brokerage) / 100;
                    x.brokerage = (x.sale_price * leader_brokerage).toFixed(2);
                    proData.push(x);
                });
                that.setData({
                    productList: that.data.productList.concat(proData),
                    page: that.data.page + 1,
                    businessListFlag: false
                });
            }
        });
    },
    goToDetail(e) {
        // if(this.data.user_status!=2&&this.data.member_audit==1){
        //   wx.showModal({
        //     title: '提示',
        //     content:'你还不是会员，请先到个人中心申请吧！',
        //     showCancel:false
        //   })
        //   return false;
        // }
        console.log(222);
        wx.navigateTo({
            url: "/localLifePackage/pages/superMarket_detail/superMarket_detail?id=" + e.currentTarget.dataset.id + "&business_id=" + this.data.id
        });
        // wx.navigateTo({
        //    url: '/pages/pro_detail/pro_detail?id=' + e.currentTarget.dataset.id,
        //  })
        },
    toDetail(e) {
        let stock = e.currentTarget.dataset.stock;
        if (!this.data.is_alive) {
            wx.showModal({
                title: "提示",
                content: "该商家休息中，无法购买!",
                showCancel: false
            });
            return;
        }
        if (stock <= 0) {
            wx.showModal({
                title: "提示",
                content: "库存不足!",
                showCancel: false
            });
            return;
        }
        let that = this;
        let pro_id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: "/localLifePackage/pages/pro_detail/pro_detail?merchant_id=" + that.data.id + "&pro_id=" + pro_id
        });
    },
    getModeName: function() {
        let that = this;
        common.request({
            endpoint: "Localbusiness/common/merchant-agreement",
            method: "post",
            data: {},
            success: res => {
                // console.log(res);
                that.setData({
                    module_name: res.extra.module_name
                });
            }
        });
    },
    showImage: function(e) {
        let imageSrc = e.currentTarget.dataset.src;
        wx.previewImage({
            urls: imageSrc
        });
    },
    gotoFace: function() {
        wx.navigateTo({
            url: `/localLifePackage/pages/payMoney/payMoney?id=${this.data.id}`
        });
    },
    //领取优惠劵
    reviewCoupon: function(e) {
        var id = e.currentTarget.dataset.id;
        common.request({
            endpoint: "v1/Localbusiness/merchant/voucher-draw",
            method: "post",
            data: {
                openid: wx.getStorageSync("user").openid,
                vor_id: id
            },
            success: res => {
                wx.showToast({
                    icon: "success",
                    title: "领取成功"
                });
            },
            fail(res) {
                wx.showToast({
                    icon: "none",
                    title: res.message
                });
            }
        });
    },
    //添加购物车
    join_cart: function(e) {
        let that = this;
        var {item: item, key: key} = e.currentTarget.dataset;
        if (item.spec_type == 0) {
            //单规格
            e.currentTarget.dataset.item.sku_id = item.skus[0].id;
            e.currentTarget.dataset.item.spu_id = item.id;
            this.changeCart(e);
        } else {
            var skus = item.skus;
            var details = item;
            var sku_attribute = that.selectingSku(item.skuAttribute);
            details.sku_attribute = sku_attribute;
            console.log(skus);
            this.setData({
                skus: skus,
                details: details,
                alert: 1,
                sku_info: skus[0],
                buy_num: 1
            });
        }
    },
    /** 
    * 选择 sku
    */
    selectingSku: function(attribues) {
        attribues.forEach(x => {
            x.attribute_value_list = [];
            var id = x.attribute_key.id;
            x.attribute_value.map((item, index) => {
                x.attribute_value_list.push({
                    value: item,
                    selected: false
                });
                x.attribute_value_list[0].selected = true;
            });
        });
        return attribues;
    },
    addSkuAttribute: function(e) {
        let key_id = parseInt(e.currentTarget.dataset.key_id);
        let value_id = parseInt(e.currentTarget.dataset.value_id);
        let a_key_index = parseInt(e.currentTarget.dataset.a_key_index);
        let a_value_index = parseInt(e.currentTarget.dataset.a_value_index);
        let attribute = this.data.details.sku_attribute;
        attribute = this.selectSku(attribute, a_key_index, a_value_index);
        var skus = this.data.skus;
        skus = this.reBlanceSku(skus, attribute);
        console.log(skus);
        let sku_info = this.getProductBySku(this.data.details.skus, skus);
        this.setData({
            skus: skus,
            ["details.sku_attribute"]: attribute,
            sku_info: sku_info
        });
    },
    getProductBySku: function(sku_products, skus) {
        var sku_info = {};
        sku_products.map(item => {
            if (item.spec_code == skus) {
                sku_info = item;
            }
        });
        return sku_info;
    },
    /** 
  * 重平衡 sku
  * key_id: integer
  */
    reBlanceSku: function(skus, attribute) {
        var t = [];
        attribute.map(item => {
            var attribute_value_list = item.attribute_value_list;
            attribute_value_list.map((sItem, sIndex) => {
                if (sItem.selected) {
                    t.push(item.attribute_key.id + "-" + sIndex);
                }
            });
        });
        return t.join(",");
        //  attribute.map
        },
    /** 
   * 选择 sku
   */
    selectSku: function(attribues, a_index, v_index = 0) {
        if (attribues[a_index]) {
            let values = attribues[a_index].attribute_value_list;
            values = values.map(item => {
                item.selected = false;
                return item;
            });
            values[v_index].selected = true;
            attribues[a_index].attribute_value_list = values;
        }
        return attribues;
    },
    add_count: function(e) {
        var buy_num = this.data.buy_num;
        var stock_num = e.currentTarget.dataset.stock;
        buy_num += 1;
        this.setData({
            buy_num: buy_num
        });
    },
    reduce_count: function() {
        var buy_num = this.data.buy_num;
        if (buy_num <= 1) {
            return false;
        }
        buy_num -= 1;
        this.setData({
            buy_num: buy_num
        });
    },
    join_goods: function() {
        var id = this.data.details.id;
        var sku_id = this.data.sku_info.id;
        var buy_num = this.data.buy_num;
        var e = {
            currentTarget: {
                dataset: {
                    key: buy_num,
                    item: {
                        sku_id: sku_id,
                        id: id
                    }
                }
            }
        };
        this.changeCart(e);
    },
    //加减购物车-
    changeCart: function(e) {
        let that = this;
        var {item: item, key: key} = e.currentTarget.dataset;
        common.request({
            endpoint: "v1/Supermarket/cart/add",
            method: "post",
            data: {
                add_quantity: key,
                sku_id: item.sku_id,
                id: item.id,
                business_id: that.data.id
            },
            success: res => {
                if (key > 0) {
                    wx.showToast({
                        icon: "none",
                        title: "加入购物车成功"
                    });
                }
                that.getCateList();
            },
            fail(res) {
                wx.showToast({
                    icon: "none",
                    title: res.message
                });
            }
        });
    },
    //隐藏购物车
    hiddenCart: function() {
        let that = this;
        that.setData({
            cartBox: false
        });
    },
    //显示购物车
    showCart: function() {
        let that = this;
        that.setData({
            cartBox: true
        });
    },
    //获取购物车
    getCateList: function(e) {
        let that = this;
        common.request({
            endpoint: "v1/Supermarket/cart/products",
            method: "post",
            header: {
                business_id: that.data.id
            },
            data: {
                business_id: that.data.id
            },
            success: res => {
                var details = res.extra;
                that.setData({
                    cateList: details.product,
                    total_amount: details.total_amount,
                    total_num: details.total_num,
                    alert: 0
                });
            },
            fail(res) {}
        });
    },
    //关闭
    close_alert: function() {
        this.setData({
            alert: 0
        });
    },
    //切换
    changeMoudle: function(e) {
        this.setData({
            current: e.currentTarget.dataset.key
        });
        if (this.data.current == "tab1") {
            this.setData({
                supperMarketGoods: [],
                pageSuper: 1
            });
            this.getfirstClass();
            //获得商超一级分类
                } else {
            this.setData({
                productList: [],
                page: 1
            });
            this.getBusinessInfo();
            //获取商品列表信息
                }
    },
    makePhone: function(e) {
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone
        });
    },
    order: function(e) {
        var cateList = this.data.cateList;
        if (!cateList.length) {
            wx.showToast({
                icon: "none",
                title: "请选择商品后下单"
            });
            return false;
        }
        var sku_item = [];
        cateList.map(item => {
            sku_item.push(item.sku_id + "," + item.num);
        });
        wx.navigateTo({
            url: "/localLifePackage/pages/orderPay/orderPay?sku_item=" + sku_item.join("|") + "&id=" + this.data.id
        });
    },
    /**
   * 清空购物车
   */
    emptyCart: function() {
        let that = this;
        common.request({
            endpoint: "v1/Supermarket/cart/empty",
            method: "post",
            header: {
                business_id: that.data.id
            },
            data: {
                business_id: that.data.id
            },
            success: res => {
                wx.showToast({
                    icon: "none",
                    title: "购物车清空成功"
                });
                this.getCateList();
            }
        });
    },
    onPgaeTap: function(e) {
        wx.reLaunch({
            url: e.currentTarget.dataset.url
        });
    }
});